//
//  NDIDCardViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/28.
//

import SwiftUI

class NDIDCardViewModel: ObservableObject {
    
    let orderNum: String
    let productId: Int
    
    var idStartTime = 0
    var faceStartTime = 0
    
    init(orderNum: String, productId: Int, stepType: IDCardStepType) {
        self.orderNum = orderNum
        self.productId = productId
        self.stepType = stepType
    }
    
    @Published var productIDCardModel: ProductIDCardModel?
    @Published var customerDetailInfoModel: CustomerDetailInfoModel?
    @Published var isLoading = false
    @Published var errorMessage: String?
    @Published var showCardInfoAlert = false
    @Published var showDatePickerAlert = false
    @Published var realName: String = ""
    @Published var idNumber: String = ""
    @Published var birthday: String = ""
    @Published var uploadFaceSuccess = false
    
    @Published var arrowPosition: CGFloat = 0.15
    @Published var stepType: IDCardStepType = .upload {
        didSet {
            switch stepType {
            case .upload:
                arrowPosition = 0.15
            case .faceReco:
                arrowPosition = 0.5
            case .completed:
                break
            }
        }
    }
    
    @Published var saveCardInfoSucces = false
    
    var selectedDate: Date {
        set {
            birthday = DateFormatterUtility.shared.string(from: newValue)
        }
        get {
            return DateFormatterUtility.shared.date(from: birthday) ?? Date()
        }
    }
    
    func requestCustomerDetailInfo() {
        isLoading = true
        errorMessage = nil
        
        NDRequestManager.requestCustomerDetailInfo(productId: productId) { [weak self] detailInfoModel, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = error
                    return
                }
                
                guard let detailInfoModel = detailInfoModel else {
                    self.errorMessage = "no data"
                    return
                }
                
                self.customerDetailInfoModel = detailInfoModel
                
                if let scabern = detailInfoModel.scabern,
                   let ventrfic = scabern.ventrfic,
                   ventrfic == 1 {
                    self.stepType = .faceReco
                }
                
                if let tribaceous = detailInfoModel.tribaceous,
                   let ventrfic = tribaceous.ventrfic,
                   ventrfic == 1 {
                    self.stepType = .completed
                }

                if let paternacle = detailInfoModel.scabern?.paternacle,
                   let name = paternacle.interestacle {
                    self.realName = name
                }
                
                if let paternacle = detailInfoModel.scabern?.paternacle,
                   let idNum = paternacle.comeie {
                    self.idNumber = idNum
                }
                
                if let paternacle = detailInfoModel.scabern?.paternacle,
                   let birthday = paternacle.aboveress,
                   birthday.count > 0,
                   birthday != "//"  {
                    self.birthday = birthday
                }
            }
        }
    }
    
    func uploadImage(image: UIImage) {
        
        isLoading = true
        errorMessage = nil
        productIDCardModel = nil
        showCardInfoAlert = false
        uploadFaceSuccess = false
        
        guard let data = UIImage.compress(image, maxKB: 400) else { return }
        NDRequestManager.uploadImageData(imageData: data, stepType: stepType) { [weak self] idCardModel, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                
                if let error = error {
                    self.errorMessage = error
                    self.isLoading = false
                    return
                }
                
                guard let idCardModel = idCardModel else {
                    self.errorMessage = "failed"
                    self.isLoading = false
                    return
                }
                
                self.isLoading = false
    
                if self.stepType == .upload {
                    self.showCardInfoAlert = true
                    self.productIDCardModel = idCardModel
                    self.realName = idCardModel.interestacle ?? ""
                    self.idNumber = idCardModel.comeie ?? ""
                    if let birthday = idCardModel.aboveress,
                       birthday.count > 0,
                       birthday != "//" {
                        self.birthday = birthday
                    } else {
                        self.birthday = ""
                    }
                } else {
                    self.uploadFaceSuccess = true
                    
                    NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .faceCard,
                                                             productId: self.productId,
                                                             orderNum: self.orderNum,
                                                             startTimeStamp: self.faceStartTime,
                                                             endTimeStamp: Int(Date().timeIntervalSince1970))
                }
            }
        }
    }
    
    func saveCardInfo() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
            guard let self = self else { return }
            self.errorMessage = nil
            self.isLoading = true
            self.saveCardInfoSucces = false
            if WJAppEnvironment.shared.currentCountry == .india {
                NDRequestManager.requestSaveIdCardInfo(birthday: birthday, identifyNum: idNumber, name: realName) { [weak self] success, msg, error in
                    guard let self = self else { return }
                    DispatchQueue.main.async {
                        self.isLoading = false
                        
                        if let error = error {
                            self.errorMessage = error
                            return
                        }
                        
                        guard let success = success, success == true else { return  }
                        
                        self.saveCardInfoSucces = success
                    }
                }
            } else {
                let phoneNumber = NDUserDefaults.shared.retrieveText(for: NDPhoneNumberKey) ?? ""
                NDRequestManager.requestSaveIdCardInfo_id(birthday: birthday, identifyNum: idNumber, name: realName, phoneNum: phoneNumber, orderNum: orderNum, productId: productId) { [weak self] success, msg, error in
                    guard let self = self else { return }
                    DispatchQueue.main.async {
                        self.isLoading = false
                        
                        if let error = error {
                            self.errorMessage = error
                            return
                        }
                        
                        guard let success = success, success == true else { return  }
                        
                        self.saveCardInfoSucces = success
                        
                        NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .IdCard,
                                                                 productId: self.productId,
                                                                 orderNum: self.orderNum,
                                                                 startTimeStamp: self.idStartTime,
                                                                 endTimeStamp: Int(Date().timeIntervalSince1970))
                    }
                }
            }
        }
    }
}

